package com.activity.fragment;

import static com.growingio.android.sdk.track.utils.ThreadUtils.runOnUiThread;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.activity.content.GoodsDetail;
import com.activity.content.SecGoodsDetail;
import com.activity.login.LoginActivity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.login.R;
import com.tools.Address;
import com.tools.CommonDialog;
import com.tools.CommonThings;
import com.tools.LoadListView;
import com.tools.OkHttp3;
import com.tools.editspinner.EditSpinner;
import com.tools.goods.Goods;
import com.tools.goods.GoodsAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GoodsFragment extends Fragment {
    private EditSpinner detailSpinner;
    private TextView search;
    private LoadListView listView;

    private JSONObject listJSON; //goods list
    private int total, page = 1;
    private ArrayList<Goods> goodsList = new ArrayList<>();

    //secGoods名称list，绑定editSpinner
    private ArrayList<String> goodsNameList = new ArrayList<>();
    private HashMap<String, String> NameIdMap = new HashMap<>();

    private boolean isHave = false;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 0x001:
                    JSONObject listObject = listJSON.getJSONObject("data");
                    listView.setRefreshTime(listJSON.getString("time"));
                    JSONArray itemsArray = listObject.getJSONArray("items");
                    for (int i=0; i<itemsArray.size(); i++){
                        JSONObject goodsObject = itemsArray.getJSONObject(i);
                        Goods goods = new Goods();
                        String id = goodsObject.getString("id");
                        String name = goodsObject.getString("goodsName");

                        goods.setId(id);
                        goods.setName(name);
                        goods.setGoodsCode(goodsObject.getString("goodsCode"));
                        goods.setProductDeadline(goodsObject.getInteger("productDeadline"));
                        goods.setAnnualInterestRate(goodsObject.getDouble("annualInterestRate"));
                        goods.setMinAmount(goodsObject.getInteger("minAmount"));
                        goods.setIncreasingAmount(goodsObject.getInteger("increasingAmount"));
                        goods.setLimitForOne(goodsObject.getInteger("limitForOne"));
                        goods.setLimitForDay(goodsObject.getInteger("limitForDay"));
                        goods.setRiskGrade(goodsObject.getInteger("riskGrade"));
                        goods.setValueDate(goodsObject.getString("valueDate"));
//                        goods.setInterestSettlementWay(goodsObject.getInteger("interestSettlementWay"));
                        goods.setDueDate(goodsObject.getString("dueDate"));

                        goodsList.add(goods);
                    }

                    GoodsAdapter goodsAdapter = new GoodsAdapter(getActivity(), R.layout.goods_item, goodsList);
                    listView.setAdapter(goodsAdapter);
                    detailSpinner.setDataList(goodsNameList);
                    break;

                case 0x002:
                    JSONObject listObject1 = listJSON.getJSONObject("data");
                    listView.setRefreshTime(listJSON.getString("time"));
                    JSONArray itemsArray1 = listObject1.getJSONArray("items");
                    for (int i=0; i<itemsArray1.size(); i++){
                        JSONObject goodsObject = itemsArray1.getJSONObject(i);
                        Goods goods = new Goods();
                        String id = goodsObject.getString("id");
                        String name = goodsObject.getString("goodsName");

                        goods.setId(id);
                        goods.setName(name);
                        goods.setGoodsCode(goodsObject.getString("goodsCode"));
                        goods.setProductDeadline(goodsObject.getInteger("productDeadline"));
                        goods.setAnnualInterestRate(goodsObject.getDouble("annualInterestRate"));
                        goods.setMinAmount(goodsObject.getInteger("minAmount"));
                        goods.setIncreasingAmount(goodsObject.getInteger("increasingAmount"));
                        goods.setLimitForOne(goodsObject.getInteger("limitForOne"));
                        goods.setLimitForDay(goodsObject.getInteger("limitForDay"));
                        goods.setRiskGrade(goodsObject.getInteger("riskGrade"));
                        goods.setValueDate(goodsObject.getString("valueDate"));
//                        goods.setInterestSettlementWay(goodsObject.getInteger("interestSettlementWay"));
                        goods.setDueDate(goodsObject.getString("dueDate"));

                        goodsList.set(i, goods);
                    }

                    GoodsAdapter goodsAdapter1 = new GoodsAdapter(getActivity(), R.layout.goods_item, goodsList);
                    listView.setAdapter(goodsAdapter1);
                    break;
            }
            return false;
        }
    });

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goods,container,false);
        detailSpinner = view.findViewById(R.id.fragment_goods_editSpinner);
        search = view.findViewById(R.id.fragment_goods_search);
        listView = view.findViewById(R.id.fragment_goods_listView);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        String state = Objects.requireNonNull(getActivity()).getIntent().getStringExtra("state");

        getGoodsList(page, 20, 0x001);
        listView.setLoadOver();

        //得到所有产品名称和id
        getGoodsInfo();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (("1").equals(state)){
                    Goods goods = goodsList.get(position-1);
                    Intent intent = new Intent(getActivity(), GoodsDetail.class);
                    intent.putExtra("goods", (Parcelable) goods);
                    startActivity(intent);
                }else {
                    initDialog();
                }
            }
        });

        listView.setOnRefreshListener(new LoadListView.OnRefreshListener() {
            @Override
            public void onPullRefresh() {
                if (("1").equals(state)){
                    getGoodsList(page, 20, 0x002);
                    getGoodsInfo();
                }else {
                    initDialog();
                }
            }
        });

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (("1").equals(state)){
                    if (detailSpinner.getText().toString().length() < 1){
                        Toast.makeText(getActivity(), "请输入产品名称！", Toast.LENGTH_SHORT).show();
                    } else {
                        String name = detailSpinner.getText();
                        for (Goods goods : goodsList){
                            if (name.equals(goods.getName())){
                                isHave = true;
                                Intent intent = new Intent(getActivity(), GoodsDetail.class);
                                intent.putExtra("goods", (Parcelable) goods);
                                startActivity(intent);
                            }
                        }
                        if (!isHave){
                            Toast.makeText(getActivity(), "无此产品或请刷新重试", Toast.LENGTH_SHORT).show();
                        }
                    }
                }else {
                    initDialog();
                }
            }
        });
    }

    private void getGoodsList(int page, int num, int msg){
        JSONObject jsonObject = new JSONObject();
        JSONObject pageJson = new JSONObject();
        JSONObject sortJson = new JSONObject();
        JSONObject queryJson = new JSONObject();
        pageJson.put("current", String.valueOf(page));
        pageJson.put("size", String.valueOf(num));

        jsonObject.put("page", pageJson);
        jsonObject.put("sort", sortJson);
        jsonObject.put("query", queryJson);
        RequestBody body = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), jsonObject.toJSONString());

        OkHttp3.sendOkHttpPostRequest(Address.getGoodsList(), body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                if (res.charAt(0) != '{'){
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "您的请求过于频繁，请稍后再访问", Toast.LENGTH_SHORT).show();
                            listView.setRefreshTime(listJSON.getString("time"));
                        }
                    });
                }else {
                    listJSON = JSONObject.parseObject(res);
                    if (listJSON.getString("code").charAt(0) == '2'){
                        Log.d("goodsList", listJSON.toString());
                        handler.sendEmptyMessage(msg);
                    }else if (listJSON.getString("code").charAt(0) == '5'){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), listJSON.getString("message"),Toast.LENGTH_SHORT).show();
                            }
                        });
                    }else{
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getActivity(), "连接出错了",Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                }
            }
        });
    }

    private void getGoodsInfo(){
        RequestBody body = RequestBody.create(null, "");

        OkHttp3.sendOkHttpPostRequest(Address.getGoodsInfo(), body, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getActivity(),"服务器连接失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                JSONObject listJSON = JSONObject.parseObject(res);
                Log.d("goodsInfo", listJSON.toString());
                if (listJSON.getString("code").charAt(0) == '2'){
                    JSONArray dataJSON = listJSON.getJSONArray("data");
                    for (int i =0; i<dataJSON.size(); i++){
                        goodsNameList.add(dataJSON.getJSONObject(i).getString("name"));
                        NameIdMap.put(dataJSON.getJSONObject(i).getString("name"), dataJSON.getJSONObject(i).getString("id"));
                    }
                }
            }
        });
    }

    private void initDialog(){
        CommonDialog dialog = new CommonDialog(getContext());
        dialog.setTitle("登录提醒");
        dialog.retainEdit(false);
        dialog.setMessage("是否进行登录");
        dialog.setOnClickBottomListener(new CommonDialog.OnClickBottomListener() {
            @Override
            public void onPositiveClick() {
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            }

            @Override
            public void onNegativeClick() {
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}